package com.atguigu.lease.web.admin.controller.apartment;


import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.model.enums.ReleaseStatus;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


@Tag(name = "公寓信息管理")
@RestController
@RequestMapping("/admin/apartment")
public class ApartmentController {

    @Autowired
    private ApartmentInfoService apartmentInfoService;

    @Autowired
    private ApartmentFacilityService apartmentFacilityService;

    @Autowired
    private ApartmentLabelService apartmentLabelService ;

    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService ;

    @Autowired
    private GraphInfoService graphInfoService ;

    @Autowired
    private RoomInfoService roomInfoService ;



    @Operation(summary = "保存或更新公寓信息")
    @PostMapping("saveOrUpdate")
    public Result saveOrUpdate(@RequestBody ApartmentSubmitVo apartmentSubmitVo) {

        //如果id不为null，说明要进行修改操作。那么修改之前需要将之前的旧关系全部删除
        if(apartmentSubmitVo.getId()!=null){
            Long apartmentId = apartmentSubmitVo.getId();
            //删除旧的配套信息
            apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>().eq(ApartmentFacility::getApartmentId,apartmentId));
            //删除旧的标签信息
            apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId,apartmentId));
            //删除旧的杂费值信息
            apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId,apartmentId));
            //删除旧的图片信息
            graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId,apartmentId).eq(GraphInfo::getItemType,ItemType.APARTMENT));

        }

        //1.保存公寓本身的基本信息
        apartmentInfoService.saveOrUpdate(apartmentSubmitVo);

        //2.保存关系表数据：配套、标签、杂费值
        //2-1. 配套
        apartmentFacilityService.saveOrUpdateBatch(apartmentSubmitVo.getFacilityInfoIds()
                                                    .stream()
                                                    .map(ApartmentFacility.builder().apartmentId(apartmentSubmitVo.getId())::facilityId)
                                                    .map(ApartmentFacility.ApartmentFacilityBuilder::build)
                                                    .collect(Collectors.toList()));

        //2-2. 标签
        apartmentLabelService.saveOrUpdateBatch(apartmentSubmitVo.getLabelIds()
                                                    .stream()
                                                    .map(labelId->new ApartmentLabel(apartmentSubmitVo.getId(),labelId))
                                                    .collect(Collectors.toList()));

        //2-3. 杂费值
        apartmentFeeValueService.saveOrUpdateBatch(apartmentSubmitVo.getFeeValueIds()
                                                    .stream()
                                                    .map(feeValueId->new ApartmentFeeValue(apartmentSubmitVo.getId(),feeValueId))
                                                    .collect(Collectors.toList()));

        //2-4. 保存这个公寓的图片信息
        graphInfoService.saveOrUpdateBatch(apartmentSubmitVo.getGraphVoList().stream().map(graphVo->{
            GraphInfo graphInfo = new GraphInfo();
            graphInfo.setUrl(graphVo.getUrl());
            graphInfo.setName(graphVo.getName());
            graphInfo.setItemType(ItemType.APARTMENT);
            graphInfo.setItemId(apartmentSubmitVo.getId());
            return graphInfo ;
        }).collect(Collectors.toList()));

        return Result.ok();
    }

    @Operation(summary = "根据条件分页查询公寓列表")
    @GetMapping("pageItem")
    public Result<IPage<ApartmentItemVo>> pageItem(@RequestParam long current, @RequestParam("size") long size, ApartmentQueryVo queryVo) {
        IPage<ApartmentItemVo> apartmentItemVoPage = apartmentInfoService.pageItem(Page.of(current,size) , queryVo);
        return Result.ok(apartmentItemVoPage);
    }

    @Operation(summary = "根据ID获取公寓详细信息")
    @GetMapping("getDetailById")
    public Result<ApartmentDetailVo> getDetailById(@RequestParam Long id) {
        //1.查询公寓的基本信息
        ApartmentInfo apartmentInfo = apartmentInfoService.getById(id);

        //2.查询公寓关联的配套信息
        List<FacilityInfo> facilityInfoList = apartmentFacilityService.getFacilityInfoListByApartmentId(id);

        //3.查询公寓关联的标签信息
        List<LabelInfo> labelInfoList = apartmentLabelService.getLabelInfoListByApartmentId(id);

        //4.查询公寓关联的杂费值信息
        List<FeeValueVo> feeValueVoList = apartmentFeeValueService.getFeeValueVoList(id);

        //5.查询公寓关联的图片信息
        List<GraphInfo> graphInfoList = graphInfoService.list(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemType,ItemType.APARTMENT).eq(GraphInfo::getItemId,id));
        List<GraphVo> graphVoList = graphInfoList.stream().map(graphInfo -> {
            GraphVo graphVo = new GraphVo();
            BeanUtils.copyProperties(graphInfo,graphVo);
            return graphVo ;
        }).collect(Collectors.toList());


        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        BeanUtils.copyProperties(apartmentInfo,apartmentDetailVo);
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        apartmentDetailVo.setLabelInfoList(labelInfoList);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);
        apartmentDetailVo.setGraphVoList(graphVoList);

        return Result.ok(apartmentDetailVo);
    }

    @Operation(summary = "根据id删除公寓信息")
    @DeleteMapping("removeById")
    public Result removeById(@RequestParam Long id) {
        //0.删除公寓信息之前，需要确保这个公寓下面没有状态正常的房间。否则抛异常提示“先删子集”
        long roomCount = roomInfoService.count(new LambdaQueryWrapper<RoomInfo>().eq(RoomInfo::getApartmentId, id));
        if(roomCount>0){
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }


        //1.删除公寓基本信息
        apartmentInfoService.removeById(id);

        //2.删除公寓关联信息
        //2-1. 配套
        apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>().eq(ApartmentFacility::getApartmentId,id));
        //2-2. 标签
        apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId,id));
        //2-3. 杂费值
        apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId,id));
        //2-4. 图片
        graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemType,ItemType.APARTMENT).eq(GraphInfo::getItemId,id));

        return Result.ok();
    }

    @Operation(summary = "根据id修改公寓发布状态")
    @PostMapping("updateReleaseStatusById")
    public Result updateReleaseStatusById(@RequestParam Long id, @RequestParam ReleaseStatus status) {
        apartmentInfoService.update(new LambdaUpdateWrapper<ApartmentInfo>().set(ApartmentInfo::getIsRelease,status).eq(ApartmentInfo::getId,id));
        return Result.ok();
    }

    @Operation(summary = "根据区县id查询公寓信息列表")
    @GetMapping("listInfoByDistrictId")
    public Result<List<ApartmentInfo>> listInfoByDistrictId(@RequestParam Long id) {
        return Result.ok(apartmentInfoService.list(new LambdaQueryWrapper<ApartmentInfo>().eq(ApartmentInfo::getDistrictId,id)));
    }
}














